package My.project.Ui.Activity;

import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import My.project.Ui.CameraPreview;
import My.project.Ui.R;
import My.project.Util.*;

/**
 * This activity is used to record video.
 * It can provide a preview of the camera.
 * Once stopped, it will automatically switch to 
 * another activity to upload the video.
 * @author Bell
 *
 */
public class RecordActivity extends Activity {
	
	private Camera mCamera = null;
	private CameraPreview mPreview= null;
	private MediaRecorder mMediaRecorder = null;
	private boolean isRecording = false;
	private ImageButton captureButton = null;
	private String filepath = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record); 
		
		// Check if there is a camera
		if(checkCameraHardware(this)){
			
			// Get the camera instance
			mCamera = getCameraInstance();
			
			// display the view of the camera
			mPreview = new CameraPreview(this, mCamera);
			FrameLayout preview = (FrameLayout) findViewById(
					R.id.camera_preview);
			preview.addView(mPreview);
			
			// Add a listener to the record button
			captureButton = (ImageButton) findViewById(R.id.button_capture);
			captureButton.setOnClickListener(
			    new View.OnClickListener() {
			        public void onClick(View v) {
			            if (isRecording) {
			                // stop recording and release camera
			                mMediaRecorder.stop();  // stop the recording
			                releaseMediaRecorder(); // release the MediaRecorder object
			                mCamera.lock();         // take camera access back from MediaRecorder

			                // inform the user that recording has stopped
			                /*captureButton.setContentDescription("Record");
			                captureButton.setImageResource(R.drawable.av_play);
			                isRecording = false;*/
			                
			                // to upload activity
			                toUploadActivity();
			            } else {
			                // initialize video camera
			                if (prepareVideoRecorder()) {
			                    // Camera is available and unlocked, 
			                	// MediaRecorder is prepared,
			                    // now you can start recording
			                    mMediaRecorder.start();

			                    // inform the user that recording has started
			                    captureButton.setImageResource(R.drawable.av_stop);
			                    captureButton.setContentDescription("Stop");
			                    isRecording = true;
			                } else {
			                    // prepare didn't work, release the camera
			                    releaseMediaRecorder();
			                    // inform user
			                }
			            }
			        }
			    }
			);
		}
	}
	
	/** Check if this device has a camera */
	private boolean checkCameraHardware(Context context) {
	    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
	        // this device has a camera
	        return true;
	    } else {
	        // no camera on this device
	        return false;
	    }
	}
	
	/** A safe way to get an instance of the Camera object. */
	public static Camera getCameraInstance(){
	    Camera c = null;
	    try {
	        c = Camera.open(); // attempt to get a Camera instance
	    }
	    catch (Exception e){
	        // Camera is not available (in use or does not exist)
	    }
	    return c; // returns null if camera is unavailable
	}
	
	/** Prepare the video recorder. */
	private boolean prepareVideoRecorder(){

	    mMediaRecorder = new MediaRecorder();

	    // Step 1: Unlock and set camera to MediaRecorder
	    mCamera.unlock();
	    mMediaRecorder.setCamera(mCamera);

	    // Step 2: Set sources
	    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
	    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

	    // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
	    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
	    // default output format is mp4, encoding is mp4-sp. Can be changed by setOutputFormat(), 
	    // setAudioEncoder() and setVideoEncoder().

	    // Step 4: Set output file
	    filepath = SaveFile.getOutputMediaFile(SaveFile.MEDIA_TYPE_VIDEO).toString();
	    mMediaRecorder.setOutputFile(filepath);

	    // Step 5: Set the preview output
	    mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

	    // Step 6: Prepare configured MediaRecorder
	    try {
	        mMediaRecorder.prepare();
	    } catch (IllegalStateException e) {
	        System.out.println("IllegalStateException preparing MediaRecorder: " + e.getMessage());
	        releaseMediaRecorder();
	        return false;
	    } catch (IOException e) {
	        System.out.println("IOException preparing MediaRecorder: " + e.getMessage());
	        releaseMediaRecorder();
	        return false;
	    }
	    return true;
	}
	
	@Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();   // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
    
    // switch to UploadActivity
    private void toUploadActivity() {
    	Intent intent = new Intent();
        intent.setClass(RecordActivity.this, UploadActivity.class);
        
        Bundle bundle = new Bundle();
        bundle.putString("filepath", filepath); // the path of the video file
        
        intent.putExtras(bundle);
        startActivity(intent);
        this.finish();
    }
}
